package com.heima.article.service.impl;

import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import lombok.extern.slf4j.Slf4j;

import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    /**
     * 计算热点文章数据
     */
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Override
    public void computeHotArticle() {
        //查询5天前的时间
        Date date = new DateTime().minusDays(5).toDate();
        //查询5天内文章数据
        List<ApArticle> apArticleListByLast5days = apArticleMapper.findApArticleListByLast5days(date);
        //计算文章分数
        List<HotArticleVo>hotArticleVoList=computeHotArticle(apArticleListByLast5days);
        //缓存30条文章
    }

    private List<HotArticleVo> computeHotArticle(List<ApArticle> apArticleListByLast5days) {
        ArrayList<HotArticleVo> hotArticleVos = new ArrayList<>();
        for (ApArticle apArticleListByLast5day : apArticleListByLast5days) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticleListByLast5day,hotArticleVo);
            Integer score=computeScore(apArticleListByLast5day);
            hotArticleVo.setScore(score);
            hotArticleVos.add(hotArticleVo);
        }
        return hotArticleVos;
    }

    private Integer computeScore(ApArticle apArticleListByLast5day) {
        Integer score=0;
        if(apArticleListByLast5day.getLikes()!=null){
            score+=apArticleListByLast5day.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticleListByLast5day.getViews()!=null){
            score+=apArticleListByLast5day.getViews();
        }
        if(apArticleListByLast5day.getComment()!=null){
            score+=apArticleListByLast5day.getComment()* ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticleListByLast5day.getCollection()!=null){
            score+=apArticleListByLast5day.getCollection()* ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
